package com.work08.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.work08.common.R;
import com.work08.pojo.User;
import com.work08.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author 绛河
 * @date 2023/6/18
 * @apiNote
 */
@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping("/register")
    public R<String> register(@RequestBody User user){
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername,user.getUsername());

        User one = userService.getOne(lambdaQueryWrapper);
        if (one!=null){
            return R.error("用户已存在！");
        }
        user.setRole(0);
        userService.save(user);
        return R.success("注册成功");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody User user){
        System.out.println(user);
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername,user.getUsername());
        User one = userService.getOne(lambdaQueryWrapper);
        if (one==null){
            return R.error("账户不存在");
        }
        if (one.getPassword().equals(user.getPassword())){
            return R.success(one);
        }else {
            return R.error("密码错误");
        }
    }

    @GetMapping("/getAllByPage")
    public R<Page> getAllByPage(String username,Integer current,Integer pageSize){
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(username!=null&&username!="",User::getUsername,username);
        Page<User> page1 = new Page<>(current,pageSize);
        userService.page(page1,lambdaQueryWrapper);
        return R.success(page1);
    }

    @PutMapping("/reset")
    public R<String> reset(Integer id){
        LambdaUpdateWrapper<User> lambdaQueryWrapper = new LambdaUpdateWrapper<>();
        lambdaQueryWrapper.set(User::getPassword,"123456");
        userService.update(lambdaQueryWrapper);
        return R.success("重置成功");
    }
}
